<template>
  <div class="dashboard-container">
    <!-- 欢迎横幅 -->
    <div class="welcome-banner">
      <div class="banner-content">
        <div class="welcome-text">
          <h1>欢迎回来，{{ userInfo.realName }}！</h1>
          <p>今天是 {{ currentDate }}，{{ currentTime }}</p>
          <p class="weather-info">
            <el-icon><Sunny /></el-icon>
            {{ weather.description }} {{ weather.temperature }}°C
          </p>
        </div>
        <div class="banner-image">
          <img src="@/assets/images/dashboard-banner.svg" alt="Dashboard" />
        </div>
      </div>
    </div>

    <!-- 数据统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :xs="12" :sm="6" :md="6" :lg="6" :xl="6">
        <div class="stats-card">
          <div class="stats-icon" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%)">
            <el-icon :size="24"><UserFilled /></el-icon>
          </div>
          <div class="stats-content">
            <div class="stats-number">{{ stats.totalGuests }}</div>
            <div class="stats-label">在住客人</div>
            <div class="stats-change positive">+{{ stats.guestChange }}%</div>
          </div>
        </div>
      </el-col>
      
      <el-col :xs="12" :sm="6" :md="6" :lg="6" :xl="6">
        <div class="stats-card">
          <div class="stats-icon" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%)">
            <el-icon :size="24"><OfficeBuilding /></el-icon>
          </div>
          <div class="stats-content">
            <div class="stats-number">{{ stats.occupancyRate }}%</div>
            <div class="stats-label">入住率</div>
            <div class="stats-change positive">+{{ stats.occupancyChange }}%</div>
          </div>
        </div>
      </el-col>
      
      <el-col :xs="12" :sm="6" :md="6" :lg="6" :xl="6">
        <div class="stats-card">
          <div class="stats-icon" style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)">
            <el-icon :size="24"><Money /></el-icon>
          </div>
          <div class="stats-content">
            <div class="stats-number">¥{{ formatNumber(stats.todayRevenue) }}</div>
            <div class="stats-label">今日收入</div>
            <div class="stats-change positive">+{{ stats.revenueChange }}%</div>
          </div>
        </div>
      </el-col>
      
      <el-col :xs="12" :sm="6" :md="6" :lg="6" :xl="6">
        <div class="stats-card">
          <div class="stats-icon" style="background: linear-gradient(135deg, #fa709a 0%, #fee140 100%)">
            <el-icon :size="24"><Star /></el-icon>
          </div>
          <div class="stats-content">
            <div class="stats-number">{{ stats.memberCount }}</div>
            <div class="stats-label">会员总数</div>
            <div class="stats-change positive">+{{ stats.memberChange }}%</div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="charts-row">
      <!-- 收入趋势图 -->
      <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span class="card-title">收入趋势</span>
              <el-radio-group v-model="revenueChartType" size="small">
                <el-radio-button label="week">本周</el-radio-button>
                <el-radio-button label="month">本月</el-radio-button>
                <el-radio-button label="year">本年</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div class="chart-container">
            <v-chart :option="revenueChartOption" :loading="chartLoading" />
          </div>
        </el-card>
      </el-col>
      
      <!-- 房型占比图 -->
      <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span class="card-title">房型分布</span>
              <el-button type="text" size="small" @click="refreshRoomTypeChart">
                <el-icon><Refresh /></el-icon>
                刷新
              </el-button>
            </div>
          </template>
          <div class="chart-container">
            <v-chart :option="roomTypeChartOption" :loading="chartLoading" />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 底部信息区域 -->
    <el-row :gutter="20" class="bottom-row">
      <!-- 今日待办 -->
      <el-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8">
        <el-card class="todo-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span class="card-title">今日待办</span>
              <el-badge :value="todoList.length" class="todo-badge" />
            </div>
          </template>
          <div class="todo-list">
            <div v-for="(item, index) in todoList" :key="index" class="todo-item">
              <div class="todo-content">
                <div class="todo-title">{{ item.title }}</div>
                <div class="todo-time">{{ item.time }}</div>
              </div>
              <div class="todo-priority" :class="item.priority"></div>
            </div>
            <div v-if="todoList.length === 0" class="empty-todo">
              <el-icon :size="48" color="#ddd"><DocumentChecked /></el-icon>
              <p>暂无待办事项</p>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <!-- 最近入住 -->
      <el-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8">
        <el-card class="recent-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span class="card-title">最近入住</span>
              <el-button type="text" size="small" @click="viewAllCheckins">
                查看全部
              </el-button>
            </div>
          </template>
          <div class="recent-list">
            <div v-for="(item, index) in recentCheckins" :key="index" class="recent-item">
              <div class="guest-avatar">
                <el-avatar :size="40">{{ item.guestName.charAt(0) }}</el-avatar>
              </div>
              <div class="guest-info">
                <div class="guest-name">{{ item.guestName }}</div>
                <div class="room-info">{{ item.roomNumber }} - {{ item.roomType }}</div>
                <div class="checkin-time">{{ formatTime(item.checkinTime) }}</div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <!-- 系统状态 -->
      <el-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8">
        <el-card class="system-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span class="card-title">系统状态</span>
              <el-tag :type="systemStatus.type" size="small">{{ systemStatus.text }}</el-tag>
            </div>
          </template>
          <div class="system-info">
            <div class="system-item">
              <span class="label">CPU使用率</span>
              <el-progress :percentage="systemInfo.cpu" :color="getProgressColor(systemInfo.cpu)" />
            </div>
            <div class="system-item">
              <span class="label">内存使用率</span>
              <el-progress :percentage="systemInfo.memory" :color="getProgressColor(systemInfo.memory)" />
            </div>
            <div class="system-item">
              <span class="label">磁盘使用率</span>
              <el-progress :percentage="systemInfo.disk" :color="getProgressColor(systemInfo.disk)" />
            </div>
            <div class="system-item">
              <span class="label">在线用户</span>
              <span class="value">{{ systemInfo.onlineUsers }} 人</span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  UserFilled,
  OfficeBuilding,
  Money,
  Star,
  Refresh,
  DocumentChecked,
  Sunny
} from '@element-plus/icons-vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart, PieChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components'
import VChart from 'vue-echarts'
import { useUserStore } from '@/stores/user'
import { getDashboardStats, getRevenueChart, getRoomTypeChart } from '@/api/dashboard'
import dayjs from 'dayjs'

// 注册ECharts组件
use([
  CanvasRenderer,
  LineChart,
  PieChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
])

const userStore = useUserStore()

// 响应式数据
const chartLoading = ref(false)
const revenueChartType = ref('week')
const currentTime = ref('')
const timer = ref(null)

// 用户信息
const userInfo = computed(() => userStore.userInfo)

// 当前日期
const currentDate = computed(() => {
  return dayjs().format('YYYY年MM月DD日 dddd')
})

// 天气信息
const weather = reactive({
  description: '晴朗',
  temperature: 25
})

// 统计数据
const stats = reactive({
  totalGuests: 156,
  guestChange: 12,
  occupancyRate: 85,
  occupancyChange: 5,
  todayRevenue: 45680,
  revenueChange: 8,
  memberCount: 1234,
  memberChange: 15
})

// 待办事项
const todoList = reactive([
  {
    title: '处理客房维修申请',
    time: '09:30',
    priority: 'high'
  },
  {
    title: '确认明日预订信息',
    time: '14:00',
    priority: 'medium'
  },
  {
    title: '更新会员积分规则',
    time: '16:30',
    priority: 'low'
  }
])

// 最近入住
const recentCheckins = reactive([
  {
    guestName: '张三',
    roomNumber: '301',
    roomType: '豪华套房',
    checkinTime: new Date()
  },
  {
    guestName: '李四',
    roomNumber: '205',
    roomType: '标准双人间',
    checkinTime: new Date(Date.now() - 30 * 60 * 1000)
  },
  {
    guestName: '王五',
    roomNumber: '102',
    roomType: '商务套房',
    checkinTime: new Date(Date.now() - 60 * 60 * 1000)
  }
])

// 系统信息
const systemInfo = reactive({
  cpu: 45,
  memory: 68,
  disk: 32,
  onlineUsers: 8
})

// 系统状态
const systemStatus = computed(() => {
  const maxUsage = Math.max(systemInfo.cpu, systemInfo.memory, systemInfo.disk)
  if (maxUsage < 50) {
    return { type: 'success', text: '运行正常' }
  } else if (maxUsage < 80) {
    return { type: 'warning', text: '负载较高' }
  } else {
    return { type: 'danger', text: '负载过高' }
  }
})

// 收入图表配置
const revenueChartOption = ref({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'cross'
    }
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
  },
  yAxis: {
    type: 'value',
    axisLabel: {
      formatter: '¥{value}'
    }
  },
  series: [
    {
      name: '收入',
      type: 'line',
      smooth: true,
      data: [8200, 9500, 7800, 11200, 13600, 15800, 12400],
      itemStyle: {
        color: '#409EFF'
      },
      areaStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            { offset: 0, color: 'rgba(64, 158, 255, 0.3)' },
            { offset: 1, color: 'rgba(64, 158, 255, 0.1)' }
          ]
        }
      }
    }
  ]
})

// 房型图表配置
const roomTypeChartOption = ref({
  tooltip: {
    trigger: 'item',
    formatter: '{a} <br/>{b}: {c} ({d}%)'
  },
  legend: {
    orient: 'vertical',
    left: 'left'
  },
  series: [
    {
      name: '房型分布',
      type: 'pie',
      radius: ['40%', '70%'],
      avoidLabelOverlap: false,
      label: {
        show: false,
        position: 'center'
      },
      emphasis: {
        label: {
          show: true,
          fontSize: '18',
          fontWeight: 'bold'
        }
      },
      labelLine: {
        show: false
      },
      data: [
        { value: 35, name: '标准单人间' },
        { value: 28, name: '标准双人间' },
        { value: 20, name: '商务套房' },
        { value: 17, name: '豪华套房' }
      ]
    }
  ]
})

// 方法
const formatNumber = (num) => {
  return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}

const formatTime = (time) => {
  return dayjs(time).format('HH:mm')
}

const getProgressColor = (percentage) => {
  if (percentage < 50) return '#67c23a'
  if (percentage < 80) return '#e6a23c'
  return '#f56c6c'
}

const updateTime = () => {
  currentTime.value = dayjs().format('HH:mm:ss')
}

const refreshRoomTypeChart = async () => {
  chartLoading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    ElMessage.success('图表已刷新')
  } catch (error) {
    ElMessage.error('刷新失败')
  } finally {
    chartLoading.value = false
  }
}

const viewAllCheckins = () => {
  // 跳转到入住管理页面
  console.log('查看全部入住记录')
}

const loadDashboardData = async () => {
  try {
    // 加载仪表板数据
    // const data = await getDashboardStats()
    // Object.assign(stats, data)
  } catch (error) {
    console.error('加载仪表板数据失败:', error)
  }
}

// 生命周期
onMounted(() => {
  updateTime()
  timer.value = setInterval(updateTime, 1000)
  loadDashboardData()
})

onUnmounted(() => {
  if (timer.value) {
    clearInterval(timer.value)
  }
})

// 监听图表类型变化
watch(revenueChartType, async (newType) => {
  chartLoading.value = true
  try {
    // 根据类型加载不同的数据
    await new Promise(resolve => setTimeout(resolve, 500))
  } finally {
    chartLoading.value = false
  }
})
</script>

<style lang="scss" scoped>
.dashboard-container {
  padding: 20px;
  background-color: var(--el-bg-color-page);
  min-height: calc(100vh - 84px);
}

.welcome-banner {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  padding: 30px;
  margin-bottom: 20px;
  color: white;
  
  .banner-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .welcome-text {
      flex: 1;
      
      h1 {
        font-size: 28px;
        font-weight: 600;
        margin: 0 0 10px 0;
      }
      
      p {
        margin: 5px 0;
        opacity: 0.9;
        
        &.weather-info {
          display: flex;
          align-items: center;
          gap: 8px;
          margin-top: 15px;
        }
      }
    }
    
    .banner-image {
      width: 200px;
      height: 120px;
      
      img {
        width: 100%;
        height: 100%;
        object-fit: contain;
      }
    }
  }
}

.stats-row {
  margin-bottom: 20px;
}

.stats-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  display: flex;
  align-items: center;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
  }
  
  .stats-icon {
    width: 60px;
    height: 60px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    margin-right: 16px;
  }
  
  .stats-content {
    flex: 1;
    
    .stats-number {
      font-size: 24px;
      font-weight: 600;
      color: var(--el-text-color-primary);
      margin-bottom: 4px;
    }
    
    .stats-label {
      font-size: 14px;
      color: var(--el-text-color-regular);
      margin-bottom: 4px;
    }
    
    .stats-change {
      font-size: 12px;
      
      &.positive {
        color: #67c23a;
      }
      
      &.negative {
        color: #f56c6c;
      }
    }
  }
}

.charts-row {
  margin-bottom: 20px;
}

.chart-card {
  height: 400px;
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .card-title {
      font-size: 16px;
      font-weight: 600;
      color: var(--el-text-color-primary);
    }
  }
  
  .chart-container {
    height: 320px;
  }
}

.bottom-row {
  .el-card {
    height: 400px;
  }
}

.todo-card {
  .todo-list {
    height: 320px;
    overflow-y: auto;
    
    .todo-item {
      display: flex;
      align-items: center;
      padding: 12px 0;
      border-bottom: 1px solid var(--el-border-color-lighter);
      
      &:last-child {
        border-bottom: none;
      }
      
      .todo-content {
        flex: 1;
        
        .todo-title {
          font-size: 14px;
          color: var(--el-text-color-primary);
          margin-bottom: 4px;
        }
        
        .todo-time {
          font-size: 12px;
          color: var(--el-text-color-placeholder);
        }
      }
      
      .todo-priority {
        width: 8px;
        height: 8px;
        border-radius: 50%;
        
        &.high {
          background-color: #f56c6c;
        }
        
        &.medium {
          background-color: #e6a23c;
        }
        
        &.low {
          background-color: #67c23a;
        }
      }
    }
    
    .empty-todo {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      height: 100%;
      color: var(--el-text-color-placeholder);
      
      p {
        margin-top: 16px;
        font-size: 14px;
      }
    }
  }
}

.recent-card {
  .recent-list {
    height: 320px;
    overflow-y: auto;
    
    .recent-item {
      display: flex;
      align-items: center;
      padding: 12px 0;
      border-bottom: 1px solid var(--el-border-color-lighter);
      
      &:last-child {
        border-bottom: none;
      }
      
      .guest-avatar {
        margin-right: 12px;
      }
      
      .guest-info {
        flex: 1;
        
        .guest-name {
          font-size: 14px;
          font-weight: 500;
          color: var(--el-text-color-primary);
          margin-bottom: 4px;
        }
        
        .room-info {
          font-size: 12px;
          color: var(--el-text-color-regular);
          margin-bottom: 2px;
        }
        
        .checkin-time {
          font-size: 12px;
          color: var(--el-text-color-placeholder);
        }
      }
    }
  }
}

.system-card {
  .system-info {
    height: 320px;
    
    .system-item {
      margin-bottom: 20px;
      
      .label {
        display: block;
        font-size: 14px;
        color: var(--el-text-color-regular);
        margin-bottom: 8px;
      }
      
      .value {
        font-size: 16px;
        font-weight: 500;
        color: var(--el-text-color-primary);
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .dashboard-container {
    padding: 10px;
  }
  
  .welcome-banner {
    padding: 20px;
    
    .banner-content {
      flex-direction: column;
      text-align: center;
      
      .banner-image {
        margin-top: 20px;
        width: 150px;
        height: 90px;
      }
    }
  }
  
  .stats-card {
    padding: 15px;
    
    .stats-icon {
      width: 50px;
      height: 50px;
      margin-right: 12px;
    }
    
    .stats-content .stats-number {
      font-size: 20px;
    }
  }
  
  .chart-card {
    height: 300px;
    
    .chart-container {
      height: 220px;
    }
  }
  
  .bottom-row .el-card {
    height: auto;
    margin-bottom: 20px;
  }
}
</style>